<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('海外仓对账单编辑')" />
    <th:block th:include="include :: businessCSS" />
    <style>
        .main-content{position: relative;}
        .topbtns{position:fixed;top: 0;width: 100%;z-index: 9999;background-color: #fff;}
        .preservationBtn{padding: 10px;margin: 0;position: fixed;top: 0;z-index: 9999;background: #fff;width: 100%;}
        .preservationBtn input{font-size: 16px;background-color: rgb(80, 138, 238);color: #fff;border: none;padding: 5px 30px;border-radius: 5px;cursor: pointer;}
        /* .layui-border-box{height: 350px !important;}
        .layui-table-body{height: 240px !important;} */
        .layui-table-tool-temp{padding-right: 30px;}
        .getDetailUpload,.getDetailUpload2{cursor: pointer;}
        .layui-table-tool-self{display: none;}
        .listext th{background:#eee;color:#3366cc;}
        .listext th,.listext td{border:solid 1px #ddd;text-align:left;padding:10px;font-size:14px;}
        .importTable{empty-cells:show;border-collapse:collapse;border-spacing:0;}
    </style>
</head>
<body class="no-skin">
<div class="main-container" id="main-container">
    <div class="main-content">
        <form class="layui-form head-form">
            <div class="north">
                <th:block th:include="include :: business_btn" />
                <th:block th:include="include :: business_tp2('top')" />
            </div>
            <div class="mid-content">
                <table class="layui-hide" id="dhtable" lay-filter="dhtable"></table>
                <script type="text/html" id="zjtoolbar">
                    <div style="padding: 16px;display: flex;justify-content: space-between;">
                        <div  style="font-weight: 700;font-size: 18px;">入库对账信息</div>
                        <div>
                            <button class="layui-btn layui-btn-normal dhicon" th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button" th:disabled="${enableEdit} == 1 ?false:true" onclick="importBtn(4)" lay-event="drbtn" id="btn-sh">入库对账单导入</button>
<!--                            <button class="layui-btn layui-btn-danger dhicon" th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button" th:disabled="${enableEdit} == 1 ?false:true" lay-event="mjbtn_save" id="btn-sh">删除</button>-->
                        </div>
                    </div>
                </script>
            </div>
            <div class="mid-content">
                <table class="layui-hide" id="kctable" lay-filter="kctable"></table>
                <script type="text/html" id="kctoolbar">
                    <div style="padding: 16px;display: flex;justify-content: space-between;">
                        <div  style="font-weight: 700;font-size: 18px;">库存对账信息</div>
                        <div>
                            <button class="layui-btn layui-btn-normal dhicon" th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button" th:disabled="${enableEdit} == 1 ?false:true" onclick="importBtn(5)" lay-event="drbtn" id="btn-sh">库存对账单导入</button>
<!--                            <button class="layui-btn layui-btn-danger dhicon" th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button" th:disabled="${enableEdit} == 1 ?false:true" lay-event="mjbtn_save" id="btn-sh">删除</button>-->
                        </div>
                    </div>
                </script>
            </div>
            <div class="mid-content">
                <table class="layui-hide" id="cktable" lay-filter="cktable"></table>
                <script type="text/html" id="cktoolbar">
                    <div style="padding: 16px;display: flex;justify-content: space-between;">
                        <div  style="font-weight: 700;font-size: 18px;">出库对账信息</div>
                        <div>
                            <button class="layui-btn layui-btn-normal dhicon" th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button" th:disabled="${enableEdit} == 1 ?false:true" onclick="importBtn(6)" lay-event="drbtn" id="btn-sh">出库对账单导入</button>
<!--                            <button class="layui-btn layui-btn-danger dhicon" th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button" th:disabled="${enableEdit} == 1 ?false:true" lay-event="mjbtn_save" id="btn-sh">删除</button>-->
                        </div>
                    </div>
                </script>
            </div>
            <th:block th:include="include :: pageFooter" />
        </form>
    </div>
</div>

<th:block th:include="include :: footer" />
<th:block th:include="include :: businessJS" />
<th:block th:include="include :: inlineJS" />
<script th:src="@{/dhecp/js/dh-toFixed.js}"></script>

<!-- 导入明细 -->
<div id="iTable" class="display_no">
    <table class="importTable listext" data-resizable-columns-id="demo-table">
        <tbody id="itbody"></tbody>
    </table>
</div>

<script th:inline="javascript">
    /*<![CDATA[*/
    var prefix = ctx + "storage/hwReconcile";
    var fields = [[${fields}]];
    var fieldsList = [[${fieldsList}]];
    var fieldsHiddenList = [[${fieldsHiddenList}]];
    var moduleTable = [[${moduleTable}]];
    var enableEdit = [[${enableEdit}]];
    //表格基础信息
    var gridColumns = [[${gridColumns}]];
    //出库信息
    var gridColumnsCk = [[${gridColumnsCk}]];
    //库存信息
    var gridColumnsKc = [[${gridColumnsKc}]];
    //入库对账模板
    var importFielSon =[[${importFields}]];
    var importFields;
    //库存对账模板
    var importF =[[${importF}]];
    //出库对账模版
    var importCk =[[${importCk}]];
    // Son列表数据
    var List=[[${List}]];
    var listData1=List ?List:[]
    // 出库列表数据
    var CkList=[[${CkList}]];
    var listData2=CkList ?CkList:[]
    // 库存列表数据
    var KcList=[[${KcList}]];
    var listData3=KcList ?KcList:[]
    var thStr;
    var $,layer,form,table,nid,noTable;
    var fieldWidth = {},		//导入列表字段宽度
        filedRequired = {},		//导入列表必填字段
        dateFiled = [],			//导入列表日期字段
        hasNull = false;		//导入数据必填字段有空值

    layui.use(['laydate','form','layer','jquery','util','element','upload','table'], function () {
        $ = layui.$, layer = layui.layer, form = layui.form, laydate = layui.laydate, util = layui.util, element = layui.element, upload = layui.upload, table = layui.table;
        beforeInit();//表单初始化之前的动作集合
        //初始化操作
        headcom3()
        nid = $('#nid').val()
        // 保存按钮事件变化
        $(function () {
            $('.tp-save').attr('onclick', '')
            $('.tp-save').attr('lay-filter', 'btn-edit')
            $('.tp-save').attr('lay-submit', true)
        })

        // 保存操作
        form.on('submit(btn-edit)', function(data){
            var is_return = false//是否中断保存
            fieldsList.map((v,i)=>{
                if(v.fieldFrontRequired){
                    if(!$('#'+v.fields).val()){
                        layer.msg(v.fieldName+'不能为空')
                        is_return=true
                    }
                }
            })
            if (listData1.length == 0){
                layer.msg("入库对账不允许为空,请核实后在操作！");
                return;
            }
            if (listData3.length == 0){
                layer.msg("库存对账不允许为空,请核实后在操作！");
                return;
            }
            if (listData2.length == 0){
                layer.msg("出库对账不允许为空,请核实后在操作！");
                return;
            }
            listData1.map((v,i)=>{
                if (v.sjRkAmount == null || v.sjRkAmount == ""){
                    is_return = true;
                    layer.msg("入库手续费(实际)不允许为空,请核实后在操作！");
                    return;
                }

                if (v.reconciliation == "对账不符"){
                    if(v.remark == "" || v.remark == null){
                        is_return = true;
                        layer.msg("库存对账的对账状况:对账不符,说明不允许为空,请核实后在操作！");
                        return;
                    }
                }
            })
            if(is_return) return;

            listData3.map((v,i)=>{
                if (v.sjKcAmount == null || v.sjKcAmount == ""){
                    is_return = true;
                    layer.msg("库存仓储费(实际)不允许为空,请核实后在操作！");
                    return;
                }

                if (v.reconciliation == "对账不符"){
                    if(v.remark == "" || v.remark == null){
                        is_return = true;
                        layer.msg("出库对账的对账状况:对账不符,说明不允许为空,请核实后在操作！");
                        return;
                    }
                }
            })
            if(is_return) return;
            listData2.map((v,i)=>{
                if (v.sjCkAmount == null || v.sjCkAmount == ""){
                    is_return = true;
                    layer.msg("出库费用(实际)不允许为空,请核实后在操作！");
                    return;
                }

                if (v.reconciliation == "对账不符"){
                    if(v.remark == "" || v.remark == null){
                        is_return = true;
                        layer.msg("出库对账的对账状况:对账不符,说明不允许为空,请核实后在操作！");
                        return;
                    }
                }
            })
            if(is_return) return;
            $.modal.loading("正在处理中，请稍后...");
            $.post("/storage/hwReconcile/editpost",{infoMap:JSON.stringify(data.field),infoItems:JSON.stringify(listData1),infoItemsKc:JSON.stringify(listData3),infoItemsCk:JSON.stringify(listData2)},function(res){
                $.modal.closeLoading()
                layer.msg(res.msg);
                if(res.code == 0){
                    window.location.href = '/storage/hwReconcile/edit?nid=' + res.data;
                }
            });
        })

        // 初始化表格
        $.tablelist.init({
            elem: '#dhtable'
            ,data: listData1
            , page: false
            , even: true
            , limit: 10000
            , totalRow: gridColumns.totalRow
            , cols: [gridColumns.gridBody]
            , toolbar: '#zjtoolbar'
            , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
            , height: '320'
            , done: function (res, curr, count) {
                listData1 = table.cache.dhtable;//每次重载都赋值更新表缓存
                fixTotal(this);//修复合计行固定列问题
                rowheight(res, curr);//修复合计行固定列问题
                detailUpload();
            },success:function(a,b,c){
                console.log(a,b,c)
            }
        });


        // 出库初始化表格
        $.tablelist.init({
            elem: '#cktable'
            ,data: listData2
            , page: false
            , even: true
            , limit: 10000
            , totalRow: gridColumnsCk.totalRow
            , cols: [gridColumnsCk.gridBody]
            , toolbar: '#cktoolbar'
            , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
            , height: '320'
            , done: function (res, curr, count) {
                listData2 = table.cache.cktable;//每次重载都赋值更新表缓存
                fixTotal(this);//修复合计行固定列问题
                rowheight(res, curr);//修复合计行固定列问题
                detailUpload();
            },success:function(a,b,c){
                console.log(a,b,c)
            }
        });

        // 库存初始化表格
        $.tablelist.init({
            elem: '#kctable'
            ,data: listData3
            , page: false
            , even: true
            , limit: 10000
            , totalRow: gridColumnsKc.totalRow
            , cols: [gridColumnsKc.gridBody]
            , toolbar: '#kctoolbar'
            , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
            , height: '320'
            , done: function (res, curr, count) {
                listData3 = table.cache.kctable;//每次重载都赋值更新表缓存
                fixTotal(this);//修复合计行固定列问题
                rowheight(res, curr);//修复合计行固定列问题
                detailUpload();
            },success:function(a,b,c){
                console.log(a,b,c)
            }
        });

        //监听单元格编辑
        table.on('edit(dhtable)', function(obj){
            if (obj.field != 'sjRkAmount'){
                return;
            }
            var tr = obj.tr;
            var regular2 = /^[0-9]+(.[0-9]{0,2})?$/
            // 单元格编辑之前的值
            var oldtext = $(tr).find("td[data-field='"+obj.field+"'] div").text();
            let fxa = true;
            //判断是否数值匹配
            listData1.map((n,m)=>{
                if (fxa == false){
                    return
                }
                if(n.sqBid == obj.data.sqBid){
                    if (!regular2.test(obj.value) && obj.value != '') {
                        n[obj.field]  = oldtext;
                        fxa = false;
                        return
                    }
                }
            })

            var data = {
                "hwReconcileSonList":[],
                "hwReconcileKcsonList":[],
                "hwReconcileCksonList":[]
            };
            data.hwReconcileSonList= listData1;
            data.hwReconcileKcsonList  = table.cache.kctable;
            data.hwReconcileCksonList = table.cache.cktable;

            update(data);
            if (!fxa){
                layer.msg("入库手续费(实际)只允许输入两位小数点的正数,请核实后在操作!")
                return
            }
        });

        //监听单元格编辑
        table.on('edit(cktable)', function(obj){
            if (obj.field != 'sjCkAmount'){
                return;
            }
            var tr = obj.tr;
            var regular2 = /^[0-9]+(.[0-9]{0,2})?$/
            // 单元格编辑之前的值
            var oldtext = $(tr).find("td[data-field='"+obj.field+"'] div").text();
            let fxa = true;
            //判断是否数值匹配
            listData2.map((n,m)=>{
                if (fxa == false){
                    return
                }
                if(n.wcBid == obj.data.wcBid) {
                    if (!regular2.test(obj.value) && obj.value != '') {
                        n[obj.field]  = oldtext;
                        fxa = false;
                        return
                    }
                }
            })
            var data = {
                "hwReconcileSonList":[],
                "hwReconcileKcsonList":[],
                "hwReconcileCksonList":[]
            };
            data.hwReconcileCksonList= listData2;
            data.hwReconcileSonList = table.cache.dhtable;
            data.hwReconcileKcsonList  = table.cache.kctable;

            update(data);
            if (!fxa){
                layer.msg("出库费用(实际)只允许输入两位小数点的正数,请核实后在操作!")
                return
            }
        });

        //监听单元格编辑
        table.on('edit(kctable)', function(obj){
            if (obj.field != 'sjKcAmount'){
                return;
            }
            var tr = obj.tr;
            var regular2 = /^[0-9]+(.[0-9]{0,2})?$/
            // 单元格编辑之前的值
            var oldtext = $(tr).find("td[data-field='"+obj.field+"'] div").text();
            let fxa = true;
            //判断是否数值匹配
            listData3.map((n,m)=>{
                if (fxa == false){
                    return
                }
                if(n.sku == obj.data.sku && n.cartonSize == obj.data.cartonSize) {
                    if (!regular2.test(obj.value) && obj.value != '') {
                        n[obj.field]  = oldtext;
                        fxa = false;
                        return
                    }
                }
            })
            var data = {
                "hwReconcileSonList":[],
                "hwReconcileKcsonList":[],
                "hwReconcileCksonList":[]
            };
            data.hwReconcileKcsonList = listData3;
            data.hwReconcileSonList = table.cache.dhtable;
            data.hwReconcileCksonList = table.cache.cktable;

            update(data);
            if (!fxa){
                layer.msg("库存仓储费(实际)只允许输入两位小数点的正数,请核实后在操作!")
                return
            }
        });
    });

    /**
     * 回调弹框事件
     */
    function getMoreAfter(fieldsList,fields,tindex,fieldName,fieldSearchType,isSearch,isLayer,res) {//弹出框赋值回调
        if(fields=='warehouseAddress'){
            if($('#hwMonth').val() == ''){
                layer.msg('月份未填写,请填写后在操作!');
                table.reload('dhtable', {data:[]});
                table.reload('cktable', {data:[]});
                table.reload('kctable', {data:[]});
                return
            }
            $.get('/storage/hwReconcile/sonList',{hwMonth:$('#hwMonth').val(),warehouseAddress:$('#warehouseAddress').val()},function(ress){
                var data = ress.data;
                if (ress.code == 0){
                    update(data);
                } else {
                    layer.msg('数据异常!');
                    return
                }
            })

        }

    }

    /**
     * 计算对账总金额
     */
    function update(data) {
        var sjAmount = 0;
        var xtAmount = 0;
        data.hwReconcileSonList.map((n,m)=>{
            if (n.sjRkAmount == null || n.sjRkAmount == undefined || n.sjRkAmount == ''){
                n.reconciliation = '对账不符'
            }else {
                var fivePercentD =  Number(n.xtRkAmount) * 0.95;
                var percentD = Number(n.xtRkAmount) * 1.05;
                //对账金额在正负百分之五范围内 对账准确
                if (fivePercentD<=Number(n.sjRkAmount)  && Number(n.sjRkAmount)<= percentD){
                    n.reconciliation = '对账相符'
                }else {
                    n.reconciliation = '对账不符'
                }
            }
            sjAmount = sjAmount + Number(n.sjRkAmount)
            xtAmount = xtAmount + Number(n.xtRkAmount)
        });
        data.hwReconcileKcsonList.map((n,m)=>{
            if (n.sjKcAmount == null || n.sjKcAmount == undefined || n.sjKcAmount == ''){
                n.reconciliation = '对账不符'
            }else {
                var fivePercentD =  Number(n.xtKcAmount) * 0.95;
                var percentD = Number(n.xtKcAmount) * 1.05;
                //对账金额在正负百分之五范围内 对账准确
                if (fivePercentD<=Number(n.sjKcAmount)  && Number(n.sjKcAmount)<= percentD){
                    n.reconciliation = '对账相符'
                }else {
                    n.reconciliation = '对账不符'
                }
            }
            sjAmount = sjAmount + Number(n.sjKcAmount)
            xtAmount = xtAmount + Number(n.xtKcAmount)
        });

        data.hwReconcileCksonList.map((n,m)=>{
            if (n.sjCkAmount == null || n.sjCkAmount == undefined || n.sjCkAmount == ''){
                n.reconciliation = '对账不符'
            }else {
                var fivePercentD =  Number(n.xtCkAmount) * 0.95;
                var percentD = Number(n.xtCkAmount) * 1.05;
                //对账金额在正负百分之五范围内 对账准确
                if (fivePercentD<=Number(n.sjCkAmount)  && Number(n.sjCkAmount)<= percentD){
                    n.reconciliation = '对账相符'
                }else {
                    n.reconciliation = '对账不符'
                }
            }
            sjAmount = sjAmount + Number(n.sjCkAmount)
            xtAmount = xtAmount + Number(n.xtCkAmount)
        });
        //设置对账总金额系统
        $('#sjAmount').val(toFixed(sjAmount,2));
        $('#xtAmount').val(toFixed(xtAmount,2));
        var fivePercent =  $('#xtAmount').val() * 0.95;
        var percent = $('#xtAmount').val() * 1.05;
        //对账金额在正负百分之五范围内 对账准确
        if (fivePercent<=$('#sjAmount').val()  && $('#sjAmount').val()<= percent){
            $('#reconciliation').val("对账相符");
        }else {
            $('#reconciliation').val("对账不符");
        }
        //入库对账信息
        table.reload('dhtable', {data:data.hwReconcileSonList});
        //库存对账信息
        table.reload('kctable', {data:data.hwReconcileKcsonList});
        //出库对账信息
        table.reload('cktable', {data:data.hwReconcileCksonList});
    }

    let isfx = 0;
    function  importBtn(data){
        if (data === 4){
            importFields = importFielSon
        }  else if (data === 5){
            importFields = importF
        } else {
            importFields = importCk
        }
        isfx = data;
        if (importFields) {
            thStr = '<tr><th><div style="width:30px;">序号</div></th>';
            $.each(importFields, function (i, val) {
                fieldWidth[val] = fieldWidth[val] ? fieldWidth[val] : 100;	//默认宽度100px
                thStr += '<th><div style="width:' + fieldWidth[val] + 'px;">' + i + '</div></th>';
            })
            thStr += '</tr>';
            layer.open({
                type: 1,
                area: ['400px', '230px'],
                fix: false,
                offset: '10%',
                maxmin: true,
                shade: 0.3,
                title: '导入',
                content: `
						<form enctype="multipart/form-data" class="mt20 mb10">
							<div class="col-xs-offset-1">
							<input type="file" id="file" name="file"/>
							<div class="mt10 pt5">
							<a onclick="$.tablelist.importTemplate('/storage/hwReconcile/exporttemplate?num=${data}')" class="btn btn-default btn-xs"><i class="dhicon dh-file-excel-o"></i> 下载模板</a>
							</div>
							<font color="red" class="pull-left mt10">提示：仅允许导入“xls”或“xlsx”格式文件！</font>
							</div>
						</form>
												`,
                btn: ['<i class="dhicon dh-check"></i> 导入', '<i class="dhicon dh-remove"></i> 取消'],
                shadeClose: true,
                zIndex: 1000,
                btn1: function (index, layero) {
                    var file = layero.find('#file');
                    if (!file[0]['value']) {
                        layer.msg("请选择文件！");
                        return false;
                    }
                    var imRes = importListExcel(file[0], importFields,'hwReconcile');
                }
            });
        } else {
            $.modal.alertWarning("后台未返回导入模板对象！");
        }
    }


    /*批量请求导入数据
     *tobj：导入数据对象
     *startNum：从第几条开始导入
     *oneImportNum：每次导入条数
     *allImportNum：总数据量
     *times：导入次数
     */
    function eachImport(tobj,startNum, oneImportNum, allImportNum, times, timeNum){
        var importObj = [];
        for(var i = startNum; i < allImportNum; i++){
            importObj.push(tobj[i]);
        }
        if (importObj.length ==0){
            layer.msg("导入数据为空,请核实后在操作!");
            showloadings(false);
            return;
        }
        $.ajaxSettings.async = false;
        var listdata;
        if (isfx === 4){
            listdata= table.cache.dhtable;
        }  else if (isfx === 5){
            listdata= table.cache.kctable;
        }else {
            listdata= table.cache.cktable;
        }
        showloadings(false);
        if(listdata.length>0){
            listdata.forEach(item => {
                if (isfx === 4){
                    let data = importObj.filter(items => items.sqBid== item.sqBid);
                    if (data.length != 0){
                        item.sjRkAmount = data[0].sjRkAmount
                    }
                }  else if (isfx === 5){
                    let data = importObj.filter(items => items.sku== item.sku && items.cartonSize== item.cartonSize);
                    if (data.length != 0){
                        item.sjKcAmount = data[0].sjKcAmount
                    }
                } else{
                    let data = importObj.filter(items => items.wcBid== item.wcBid);
                    if (data.length != 0){
                        item.sjCkAmount = data[0].sjCkAmount
                    }
                }
            });
            var data = {
                "hwReconcileSonList":[],
                "hwReconcileKcsonList":[],
                "hwReconcileCksonList":[]
            };
            if (isfx === 4){
                data.hwReconcileSonList = listdata;
                data.hwReconcileKcsonList = table.cache.kctable;
                data.hwReconcileCksonList = table.cache.cktable ;
            } else if (isfx === 5){
                data.hwReconcileKcsonList = listdata;
                data.hwReconcileSonList = table.cache.dhtable;
                data.hwReconcileCksonList = table.cache.cktable ;
            }else {
                data.hwReconcileSonList = table.cache.dhtable;
                data.hwReconcileKcsonList = table.cache.kctable;
                data.hwReconcileCksonList = listdata;
            }
            update(data);
            layer.msg("导入成功")
            setTimeout(function(){
                sessionStorage.setItem(moduleTable+'checkdata','')
                layer.closeAll();
            }, 1000);
        }else{
            layer.msg("请新增数据!");
        }
    }


</script>
</body>
</html>
